package org.springblade.modules.admin.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.modules.admin.entity.Scheduled;
import org.springblade.modules.admin.service.IScheduledService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @author zcc
 * @version 1.0
 * @date 2021/11/30 14:09
 */
@Component
public class ScheduleSetting implements SchedulingConfigurer {

	@Autowired
	private IScheduledService sysScheduledService;

	private String expression = "0 0 8 * * ?";

	private final static String TEMP = "userNote";

	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

		Scheduled serviceOne = sysScheduledService.getOne(Wrappers.<Scheduled>lambdaQuery().eq(Scheduled::getTemp, TEMP));
		expression = serviceOne.getCron();
		if (serviceOne.getStartFlag() == 1) {
			// 调度实现的时间控制
			Trigger trigger = triggerContext -> {
				CronTrigger cronTrigger = new CronTrigger(expression);
				return cronTrigger.nextExecutionTime(triggerContext);
			};
			scheduledTaskRegistrar.addTriggerTask(getRunnable(serviceOne), trigger);
		}

	}


	/**
	 * 转换首字母小写
	 *
	 * @param str
	 * @return
	 */
	public static String lowerFirstCapse(String str) {
		char[] chars = str.toCharArray();
		chars[0] += 32;
		return String.valueOf(chars);
	}

	/**
	 * runnable
	 *
	 * @param scheduleConfig
	 * @return
	 */

	private Runnable getRunnable(final Scheduled scheduleConfig) {
		return new Runnable() {
			@Override
			public void run() {
				Class<?> clazz;
				try {
					clazz = Class.forName(scheduleConfig.getClassName());
					String className = lowerFirstCapse(clazz.getSimpleName());
					Object bean = (Object) ApplicationContextHelper.getBean(className);
					Method method = ReflectionUtils.findMethod(bean.getClass(), scheduleConfig.getMethod());
					ReflectionUtils.invokeMethod(method, bean);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		};
	}


	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		this.expression = expression;
	}

}
